package com.heima.media.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocal;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    // 前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拦截从网关发送过来的请求
        // 从请求头中获取用户id
        String userIdStr = request.getHeader("userId");
         String name = request.getHeader("name");
        // 有用户id,将用户id设置到本地线程中
        if (!StringUtils.isEmpty(userIdStr)) {
            User user = new User();
            user.setUserId(Integer.parseInt(userIdStr));
            user.setName(name);
            UserThreadLocal.set(user);
        }
        return true;
    }

    // 后置拦截 响应返回给客户端之前拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}